import os
import re
import email
import imaplib
from email.utils import getaddresses

receive_host = 'imap.exmail.qq.com'
receive_port = 993
send_host = 'smtp.exmail.qq.com'
send_port = 465
user = 'medical-sc-info@novogene.com'
password="HblM70kQjVb]tYL"

client = imaplib.IMAP4_SSL(receive_host,receive_port)
client.login(user,password)

tag,data = client.list()

for box in data:
    list_response_pattern = re.compile(
        r'.(?P<flags>.*?). "(?P<delimiter>.*)" "(?P<name>.*)"'
    )
    match = list_response_pattern.match(box.decode("utf-8"))
    flags, _, mailbox_name = match.groups()
    flags = flags.replace("\\","")
    # print(f"{mailbox_name:<20}: {flags}")
    status = client.status(
    '"{}"'.format(mailbox_name),
    '(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)',
    )
    print(status)

tag,data = client.select("&UXZO1mWHTvZZOQ-/AutoPipeline")
print(tag,data)
tag,data = client.search(None,"ALL")
print(tag,data)
print(data[0].split())
# tag,data = client.fetch('65','(RFC822)')
tag,data = client.fetch('64','(RFC822)')
# print(data[0][1])
msg = email.message_from_bytes(data[0][1])
# print(msg)
print(dir(msg))
# for i in msg:
#     print(i)
#     print("-----")

# for part in msg.walk():
#     print(part)
#     print("------")

# get subject
text,enc = email.header.decode_header(msg['subject'])[0]
print(text,enc)
subject = text.decode(enc) if enc else text
print(subject)

# get recipents
tos = msg.get_all('to',[])
sender = msg.get_all("from",[])
ccs = msg.get_all("cc",[])
resent_tos = msg.get_all('resent-to', [])
resent_ccs = msg.get_all('resent-cc', [])
print(getaddresses(tos + ccs + resent_tos + resent_ccs + sender))

# get body
if msg.is_multipart():
    print("It's a mutipart!")
    for part in msg.walk():
        ctype = part.get_content_type()
        cdispo = str(part.get('Content-Disposition'))

        # skip any text/plain (txt) attachments
        if ctype == 'text/plain' and ('attachment' not in cdispo):
            body = part.get_payload(decode=True).decode("utf-8")  # decode
            break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
    body = msg.get_payload(decode=True).decode("utf-8")

print(body)

# get attachment

def get_email_attachment(self,msg):
    """
    下载邮件中的附件
    """
    attachments = []
    for part in msg.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()

        # 如果文件名为纯数字、字母时不需要解码，否则需要解码
        try:
            fileName = email.header.decode_header(fileName)[0][0].decode(email.header.decode_header(fileName)[0][1])
        except:
            pass

        # 只获取指定拓展名的附件
        extension = os.path.splitext(os.path.split(fileName)[1])[1]
        if extension not in [".xlsx"]:
            continue

        # 如果获取到了文件，则将文件保存在指定的目录下
        if fileName:
            fileName = fileName.replace(" ","_")
            if not os.path.exists(self._savedir):
                os.makedirs(self._savedir)
            filePath = os.path.join(self._savedir, fileName)
            fp = open(filePath, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()
            attachments.append(filePath)

    return attachments